function OS_Scene(host,id)
{
	this.$super=OS_Interface;
	if (this.$super(host,id)===false) return;
	delete this.$super;
	
	this.illustration=null;
	this.gradual=null;
	this.filter={r:0,g:0,b:0,a:0};
	
	var effects=
		{
			below:[],
			above:[]
		};
	var paused=false;
	
	this.isPaused=function()
	{
		return paused;
	}
	
	this.pause=function()
	{
		paused=true;
	}
	
	this.resume=function()
	{
		paused=false;
	}
	
	var window_resource=null;
	this.getWinRes=function()
	{
		return window_resource;
	}
	
	var instance=this;
	
	//活动的对话框
	var activeDialog=null;
	this.setActiveDialog=function(dialog)
	{
		activeDialog=dialog;
	}
	
	this.load=function(handler)
	{
		var children=this.resourceNode.childNodes;
		host.status.supportingRoles=[];
		for (var i=0;i<children.length;i++)
		{
			if (children[i].nodeType!=1) continue;
			var child=children[i];
			switch(child.nodeName)
			{
				case "world":
					var worldid=child.childNodes[0].nodeValue;
					this.world=OS_Resource.resource.get(worldid);
					break;
				case "environment":
					var bgmid=child.getElementsByTagName("bgm")[0].childNodes[0].nodeValue;
					this.bgm=OS_Resource.resource.get(bgmid);
					break;
				case "logic":
					var actives=child.childNodes;
					for (var j=0;j<actives.length;j++)
					{
						if (actives[j].nodeType!=1) continue;
						if (actives[j].nodeName!="act") continue;
						var active=actives[j];
						if (active.getAttribute("leading"))
						{
							if (!host.status.leadingRole)
							{
								host.status.leadingRole=OS_Resource.resource.get(active.childNodes[0].nodeValue);
							}
						}
						else
						{
							host.status.supportingRoles.push(OS_Resource.resource.get(active.childNodes[0].nodeValue));
						}
					}
					break;
				case "dialog":
					window_resource=OS_Resource.resource.get(child.childNodes[0].nodeValue);
					break;
			}
		}
		this.loaded=true;
		handler(this);
	}
	
	this.playBGM=function()
	{
		host.studio.playBGM([this.bgm],false);
	}
	
	//更新所有角色的位置
	var updatePositions=function()
	{
		var upkey=		{key:"up",value:0,time:host.status.checkKeyHold("up")||1};
		var downkey=	{key:"down",value:2,time:host.status.checkKeyHold("down")||1};
		var leftkey=	{key:"left",value:3,time:host.status.checkKeyHold("left")||1};
		var rightkey=	{key:"right",value:1,time:host.status.checkKeyHold("right")||1};
		
		var nearest=upkey;
		if (downkey.time>upkey.time) nearest=downkey;
		if (leftkey.time>upkey.time) nearest=leftkey;
		if (rightkey.time>upkey.time) nearest=rightkey;
		
		//移动主角
		if (nearest.time>1)
		{
			if (host.status.leadingRole.isInPosition())
			{
				host.status.leadingRole.faceto(nearest.value);
			}
			host.status.leadingRole.forward(null,"positionevent",function(){
				var params={};
				params.time=(new Date()).getTime();
				//触发位置更新事件
				host.status.positionTrigger.active(host.status.leadingRole,params);
			});
		}
		else
		{
			if (!host.status.leadingRole.isInPosition())
			{
				host.status.leadingRole.forward(null,"positionevent",function(){
					var params={};
					params.time=(new Date()).getTime();
					//触发位置更新事件
					host.status.positionTrigger.active(host.status.leadingRole,params);
				});
			}
			else if (host.status.checkKeyPressed("enter"))
			{
				var params={};
				params.time=(new Date()).getTime();
				//触发确认键事件
				host.status.confirmTrigger.active(host.status.leadingRole,params);
			}
		}
		
		//记录调试信息
		host.debugDataR.put("Leading Role Pos-x",host.status.leadingRole.currentPosition.x.toFixed(1));
		host.debugDataR.put("Leading Role Pos-y",host.status.leadingRole.currentPosition.y.toFixed(1));
		
		//移动配角
		for (var i=0;i<host.status.supportingRoles.length;i++)
		{
			var active_current=host.status.supportingRoles[i];
			if (!active_current.isEnable()) continue;
			
			if (active_current.wait===undefined) active_current.wait=0;
			if (active_current.wait>0)
			{
				active_current.wait--;
			}
			else if (!active_current.isInPosition())
			{
				active_current.forward();
				active_current.wait=-10;
			}
			else if (active_current.mode=="auto")
			{
				var actions=[];
				if (active_current.wait==-10)
				{
					actions.push(4);//已经移动过了就可以等待
					actions.push(5);
				}
				if (active_current.currentPosition.y/host.config.squareheight-1>=active_current.position.y) actions.push(0);
				if (active_current.currentPosition.x/host.config.squarewidth+1<active_current.position.x+active_current.scope.colspan) actions.push(1);
				if (active_current.currentPosition.y/host.config.squareheight+1<active_current.position.y+active_current.scope.rowspan) actions.push(2);
				if (active_current.currentPosition.x/host.config.squarewidth-1>=active_current.position.x) actions.push(3);
				var whattodo=actions[Math.floor(Math.random()*actions.length)];
				if (whattodo==4 || whattodo==5)
				{
					active_current.wait=Math.random()*host.config.fps*0.5+host.config.fps*0.5;
				}
				else
				{
					active_current.faceto(whattodo);
					active_current.forward();
				}
			}
			
			host.debugDataR.put("Supporting Role "+i+" Pos-x",active_current.currentPosition.x.toFixed(1));
			host.debugDataR.put("Supporting Role "+i+" Pos-y",active_current.currentPosition.y.toFixed(1));
			
		}
	}
	
	//利用时间偏移量实现动画暂停
	var calibrateEffectTime=function()
	{
		for (var la=0;la<2;la++)
		{
			if (la==0) layer="below";
			if (la==1) layer="above";
			for (var i=0;i<effects[layer].length;i++)
			{
				if (paused)
				{
					if (effects[layer][i].timeOffset===false)
					{
						effects[layer][i].timeOffset=(new Date()).getTime()-effects[layer][i].startTime;
					}
					else
					{
						effects[layer][i].startTime=(new Date()).getTime()-effects[layer][i].timeOffset;
					}
				}
				else
				{
					effects[layer][i].timeOffset=false;
				}
			}
		}
	}
	
	var update=function()
	{
		if (activeDialog!=null) 
		{
			activeDialog.interceptKey();//截取按键事件
			activeDialog.update();
		}
		else if (!!host.status.checkKeyPressed("esc"))
		{
			//如果退出键被按下了，启动游戏菜单
			var params={};
			params.position="center";
			params.width=140;
			params.height=150;
			params.text=null;
			params.key="$sceneMenuSelect_val";
			params.options=[{text:"继续游戏",value:"继续"},{text:"角色状态",value:"状态"},{text:"保存游戏",value:"保存"},{text:"退出游戏",value:"退出"}];
			params.callback=function()
			{
				var actionChoosed=host.status.V.get(params.key);
				switch(actionChoosed)
				{
					case "状态":
						var _params={};
						_params.position="center";
						_params.width=140;
						_params.height=150;
						_params.text=null;
						_params.key="$sceneMenuRoleSelect_val";
					    _params.options=[];
					    var members=host.status.team.members;
						for( var i=0;i<members.length;i++) if (members[i].appearance)
						{
					   		 _params.options.push({text:members[i].name,value:members[i].name});
						}
						_params.callback=function()
						{
							var actionChoosed=host.status.V.get(_params.key);
							switch(actionChoosed)
							{
								case "ESC":
									activeDialog=menu001;
									activeDialog.open();
									break;
								default:
								   for(var i=0;i<members.length;i++)
								   {
									   if (actionChoosed==members[i].name)
									   {
											var params2={};
											params2.position="center";
											params2.width=200;
											params2.height=300;
											params2.text=members[i].name+" "+members[i].level+"级";
											params2.key="$sceneMenuStatusSelect_val";
					    					params2.options=[];
											params2.options.push({
												text:"经验值 "+members[i].experience+"/"+members[i].experienceLimit,
												value:members[i].maxHp});
											params2.options.push({
												text:"HP值 "+members[i].hp+"/"+members[i].maxHp,
												value:members[i].maxHp});
											params2.options.push({
												text:"Mp值 "+members[i].mp+"/"+members[i].maxMp,
												value:members[i].maxMp});
											params2.options.push({
												text:"速度 "+(members[i].initialSpeed+members[i].speedAddition*(members[i].level-1)),
												value:members[i].maxMp});
											params2.options.push({
												text:"攻击力 "+(members[i].initialAttack+members[i].attackAddition*(members[i].level-1)),
												value:members[i].maxMp});
											params2.options.push({
												text:"防御力 "+(members[i].initialDefense+members[i].defenseAddition*(members[i].level-1)),
												value:members[i].maxMp});
											params2.options.push({
												text:"魔力 "+(members[i].initialMagic+members[i].magicAddition*(members[i].level-1)),
												value:members[i].maxMp});
											params2.options.push({
												text:"抵抗力 "+(members[i].initialResistance+members[i].resistanceAddition*(members[i].level-1)),
												value:members[i].maxMp});
											
											params2.callback=function()
											{
												var actionChoosed=host.status.V.get(params2.key);
												switch(actionChoosed)
												{
													case "ESC":
														activeDialog=menu002;
														activeDialog.open();
													break;
													default:
													instance.resume();
													break;
												}
											}	
											var menu003=new OS_SelectDialog(host,instance,instance.getWinRes(),params2);
											
											activeDialog=menu003;
											activeDialog.open();
										   
									   }
								   }
							}
						}
						var menu002=new OS_SelectDialog(host,instance,instance.getWinRes(),_params);
						activeDialog=menu002;
						activeDialog.open();
					    break;
					case "继续":
						instance.resume();
						break;
					case "保存":
						host.status.saveToLocal();
						var paramsSave={};
						paramsSave.position="center";
						paramsSave.width=150;
						paramsSave.height=80;
						paramsSave.words=["保存成功"];
						paramsSave.callback=function()
						{
							instance.resume();
						}
						activeDialog=new OS_TalkDialog(host,instance,instance.getWinRes(),paramsSave);
						activeDialog.open();
						break;
					case "退出":
						host.loopEndHooks.push(function()
						{
							host.changeInterface(host.config.entryInterface,"menu");
						});
						break;
					case "ESC":
						instance.resume();
						break;
				}
			}
			var menu001=new OS_SelectDialog(host,instance,instance.getWinRes(),params);
			activeDialog=menu001;
			instance.pause();
			activeDialog.open();
		} else if (!!host.status.checkKeyPressed("tab"))
		{
			host.status.team.nextActiveMember();
		}
		for (var i=0;i<host.status.supportingRoles.length;i++)
		{
			host.status.supportingRoles[i].update();
		}
		if (!paused) updatePositions();
		if (!paused) host.status.frameTrigger.active();
		calibrateEffectTime();
	}
	
	this.drawEffect=function(layer)
	{
		for (var i=0;i<effects[layer].length;i++)
		{
			var effectPlaying=effects[layer][i];
			var time=(new Date()).getTime()-effectPlaying.startTime;
			var frame=effectPlaying.effect.getFrame(time);
			if (frame===false)
			{
				effects[layer][i]=false;
			}
			else
			{
				var left=effectPlaying.col*host.config.squarewidth-effectPlaying.effect.offset.x;
				var top=effectPlaying.row*host.config.squareheight-effectPlaying.effect.offset.y;
				host.stage.draw(frame,left,top);
			}
		}
		//把播放完毕的动画从队列中去除
		index=0;
		while (index<effects[layer].length)
		{
			if (effects[layer][index]===false)
			{
				effects[layer].splice(index,1);
			}
			else
			{
				index++;
			}
		}
	}

	this.refresh=function()
	{
		update();
		host.stage.clear("#000");
		//屏幕跟随主角
		host.stage.setViewCenter(
			host.status.leadingRole.currentPosition.x+host.config.squarewidth/2,
			host.status.leadingRole.currentPosition.y+host.config.squareheight/2
		);
		this.world.drawBelowActor();
		this.drawEffect("below");
		host.status.leadingRole.actor=host.status.team.getActiveMember().sceneActor;
		host.status.leadingRole.drawSelf();
		for (var i=0;i<host.status.supportingRoles.length;i++)
		{
			host.status.supportingRoles[i].drawSelf();
		}
		this.drawEffect("above");
		this.world.drawAboveActor();
		host.stage.resetViewCenter();
		if (!!this.illustration)
		{
			host.stage.fill(OS_Resource.resource.get(this.illustration));
		}
		//实现渐变
		if (!!this.gradual)
		{
			var timeTemp=(new Date()).getTime()-this.gradual.startTime;
			if (timeTemp>this.gradual.duration || this.gradual.duration<=0)
			{
				this.filter.r=this.gradual.toR;
				this.filter.g=this.gradual.toG;
				this.filter.b=this.gradual.toB;
				this.filter.a=this.gradual.toA;
				//执行回调函数
				this.gradual.callback();
				this.gradual=null;
			}
			else
			{
				this.filter.r=Math.floor(this.gradual.fromR+(this.gradual.toR-this.gradual.fromR)*timeTemp/this.gradual.duration);
				this.filter.g=Math.floor(this.gradual.fromG+(this.gradual.toG-this.gradual.fromG)*timeTemp/this.gradual.duration);
				this.filter.b=Math.floor(this.gradual.fromB+(this.gradual.toB-this.gradual.fromB)*timeTemp/this.gradual.duration);
				this.filter.a=this.gradual.fromA+(this.gradual.toA-this.gradual.fromA)*timeTemp/this.gradual.duration;
			}
		}
		var color="rgba("+this.filter.r+","+this.filter.g+","+this.filter.b+","+this.filter.a+")";
		host.stage.fill(color);
		if (!!activeDialog) activeDialog.drawSelf();
	}
	
	this.playEffect=function(effect,row,col)
	{
		var effectPlaying={effect:effect,row:row,col:col,startTime:(new Date()).getTime(),timeOffset:false};
		effects[effect.layer].push(effectPlaying);
	}
	
	this.encode=function()
	{
		var temp={};
		temp.sceneid=this.id;
		temp.activeid=host.status.leadingRole.id;
		temp.positionX=host.status.leadingRole.currentPosition.x;
		temp.positionY=host.status.leadingRole.currentPosition.y;
		temp.distanceF=host.status.leadingRole.distanceFromLastSquare;
		temp.direction=host.status.leadingRole.direction;
		return JSON.stringify(temp);
	}
	
	this.decode=function(data)
	{
		var temp=eval("("+data+")");
		host.status.leadingRole=OS_Resource.resource.get(temp.activeid);
		host.status.leadingRole.deoccupy();
		host.status.leadingRole.currentPosition.x=temp.positionX;
		host.status.leadingRole.currentPosition.y=temp.positionY;
		host.status.leadingRole.distanceFromLastSquare=temp.distanceF;
		host.status.leadingRole.direction=temp.direction;
		host.status.leadingRole.occupy();
	}
	
}

OS_Resource.Builder.put("scene",OS_Scene);
